package com.woman.beautylive.presentation.ui.main.find.pengyouquan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.R;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.main.find.FixGridLayout;
import com.woman.beautylive.presentation.ui.main.find.MyListView;
import com.woman.beautylive.presentation.ui.main.find.PengYouQuanActivity;
import com.woman.beautylive.presentation.ui.main.find.RoundImageView;
import com.woman.beautylive.presentation.ui.main.find.String2Spanned;
import com.woman.beautylive.presentation.ui.main.find.adapter.DetailReplyAdapter;
import com.woman.beautylive.presentation.ui.main.find.adapter.ImageGridAdapter;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.DongTaiDetailBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.DongTaiListBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.MyDongTaiBean;
import com.woman.beautylive.presentation.ui.main.me.OtherUserActivity;
import com.woman.beautylive.util.Const;
import com.woman.beautylive.util.DensityUtil;
import com.woman.beautylive.util.SoftwareUtil;
import com.woman.beautylive.util.XImageLoader;

import java.util.ArrayList;
import java.util.List;

import chatemoji.FaceInputView;
import chatemoji.Spanned2String;

public class DongTaiDetailActivity extends BaseActivity implements PublishInterFace, View.OnClickListener, AdapterView.OnItemClickListener {
    RoundImageView my_me_photo;
    ImageView item_friend_commentimg, item_billboard_tag1, item_billboard_tag2;
    TextView item_billboard_name, item_billboard_contant, item_friend_time, txt_send;
    FixGridLayout li_fav_container;
    LinearLayout bottom;
    GridView li_imgContainer;
    MyListView comment_listView;
    EditText edit_content;
    String pid = null;
    private DongtaiPresenter dongtaiPrsenter;
    private PublishPresenter publishPresenter;
    private DongTaiDetailBean detailBean;
    private AlertDialog alertDialog;
    private String rid;
    ImageView detail_delete,back;
    int type = 0;
    private FaceInputView faceInputView;
    private LinearLayout faceInputContainer;
    ImageView emoji;
    private boolean isShow;
    List<DongTaiListBean.DongTaiItem.ReplyList.ReplyItem> replyList;
    private int pageNo = 1;
    private DetailReplyAdapter adapter;
    private PopupWindow mMorePopupWindow;
    String isLike = null;
    String uid;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_circle_friends;
    }

    @Override
    protected void findViews(Bundle savedInstanceState) {
        detail_delete = (ImageView) findViewById(R.id.detail_delete);
//        detail_delete.setVisibility(View.VISIBLE);

        replyList = new ArrayList<>();
        back= (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        emoji = (ImageView) findViewById(R.id.emoji);
        emoji.setOnClickListener(this);
        li_imgContainer = (GridView) findViewById(R.id.li_imgContainer);
        faceInputContainer = (LinearLayout) findViewById(R.id.faceInputContainer);
        dongtaiPrsenter = new DongtaiPresenter(this);
        publishPresenter = new PublishPresenter(this);//presenter实例化
        detail_delete.setOnClickListener(this);
        my_me_photo = (RoundImageView) findViewById(R.id.my_me_photo);
        item_friend_commentimg = (ImageView) findViewById(R.id.item_friend_commentimg);
        item_billboard_tag1 = (ImageView) findViewById(R.id.item_billboard_tag1);
        item_billboard_tag2 = (ImageView) findViewById(R.id.item_billboard_tag2);
        faceInputView = new FaceInputView(this);
        faceInputContainer.addView(faceInputView);
        faceInputView.setOnClickListener(new FaceInputListenr());
        item_billboard_name = (TextView) findViewById(R.id.item_billboard_name);
        item_billboard_contant = (TextView) findViewById(R.id.item_billboard_contant);
        item_friend_time = (TextView) findViewById(R.id.item_friend_time);
        txt_send = (TextView) findViewById(R.id.txt_send);
        txt_send.setOnClickListener(this);
        my_me_photo.setOnClickListener(this);
        li_fav_container = (FixGridLayout) findViewById(R.id.li_fav_container);

        bottom = (LinearLayout) findViewById(R.id.bottom);

        comment_listView = (MyListView) findViewById(R.id.comment_listView);

        edit_content = (EditText) findViewById(R.id.edit_content);

        pid = getIntent().getStringExtra("pid");
        uid=getIntent().getStringExtra("uid");
        faceInputView = new FaceInputView(this);

        comment_listView.setAdapter(adapter);
        getYuanTieInfo(pid);
    }

    private class FaceInputListenr implements FaceInputView.OnFaceClickListener {

        @Override
        public void selectedFace(FaceInputView.Face face) {
            int id = face.faceId;
            if (id == R.drawable.ic_face_delete_normal)// 删除按钮
            {
                int index = edit_content.getSelectionStart();
                if (index == 0)
                    return;
                Editable editable = edit_content.getText();
                editable.delete(index - 1, index);// 删除最后一个字符或表情
            } else {
                edit_content.append(Html.fromHtml("<img src='" + id + "'/>",
                        imageGetter, null));// 添加表情
            }
        }

    }

    // 输入表情需要
    Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            @SuppressWarnings("deprecation")
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };

    private void getYuanTieInfo(String pid) {

        dongtaiPrsenter.getDongTaiDetail(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, "5", "10");
    }

    void sendMyBroad(){
        Intent intent=new Intent(PengYouQuanActivity.REFRESHLIST);
        sendBroadcast(intent);
    }

    @Override
    protected void init() {

    }

    @Override
    public void showPublishResult(PublishBean data) {

    }

    @Override
    public void showUpdatePublishResult(String data) {

    }

    @Override
    public void showDeletePublishResult(String data) {
        if (data != null) {
            sendMyBroad();//通知前一个页面更新
            Toast.makeText(this, "删除成功", 0).show();
            finish();
        }
    }

    @Override
    public void showdianzanResult(String data) {
        if (isLike != null) {
            if (isLike.equals("0")) {
                Toast.makeText(this, "点赞成功", 0).show();
                li_fav_container.setVisibility(View.VISIBLE);

                isLike = "1";
            } else {
                Toast.makeText(this, "取消成功", 0).show();
                isLike = "0";
            }
            sendMyBroad();//通知前一个页面更新
            dongtaiPrsenter.getDianZanList(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, "1", "100000");
        }
    }


    @Override
    public void showDongtaiList(DongTaiListBean data) {

    }

    @Override
    public void showMyDongTaiList(List<MyDongTaiBean> list) {

    }

    @Override
    public void getDetailData(DongTaiDetailBean bean) {
        setDetailData(bean);
    }

    @Override
    public void showHuiFuOneResult(PublishBean result) {
        if (result != null) {
            if (result.getRid() != null) {
                sendMyBroad();//通知前一个页面更新

                Toast.makeText(this, "回复成功" + result, 0).show();
                dongtaiPrsenter.getHuiFuList(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, "5", "10");
            } else {
                Toast.makeText(this, "回复失败", 0).show();
            }
        } else {
            Toast.makeText(this, "回复失败", 0).show();
        }
    }

    @Override
    public void showReplyDeleteResult(String result) {
        if (result != null) {
            Toast.makeText(this, "删除回复成功", 0).show();
            sendMyBroad();//通知前一个页面更新

            dongtaiPrsenter.getHuiFuList(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, "5", "10");
        }
    }

    @Override
    public void getReplyList(DongTaiListBean.DongTaiItem.ReplyList data) {
        replyList.addAll(data.getList());
        comment_listView.setOnItemClickListener(this);
        if (adapter == null) {
            adapter = new DetailReplyAdapter(0, replyList, this);
            comment_listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getDianZanList(DongTaiListBean.DongTaiItem.ReplyList data) {
        li_fav_container.removeAllViews();
        int width = DensityUtil.dip2px(40);
        int height = DensityUtil.dip2px(40);
//        TextView imageView = new TextView(BeautyLiveApplication.getContextInstance());
//        imageView.setText("♡");
//        imageView.setTextSize(13);
//        imageView.setTextColor(getResources().getColor(R.color.md_pink_400));
//        imageView.setBackgroundResource(R.drawable.undianzan);
//        android.widget.LinearLayout.LayoutParams layoutParams2 = new android.widget.LinearLayout.LayoutParams(
//                width, height);
//        layoutParams2.setMargins(5, 5, 5, 5);
//        li_fav_container.addView(imageView, layoutParams2);
//            for (int i = 0; i < li_fav_container.getChildCount(); i++) {
//                if(i!=0) {
//                    li_fav_container.removeViewAt(i);
//                }
//            }
        if (data != null) {
            if (data.getList().size() > 0) {
                li_fav_container.setVisibility(View.VISIBLE);
                LinearLayout.LayoutParams layoutparamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutparamas.setMargins(5, -5, 5, 0);

                for (int i = 0; i < data.getList().size(); i++) {
                    TextView text = new TextView(DongTaiDetailActivity.this);
                    text.setTextColor(getResources().getColor(R.color.md_pink_600));
                    text.setTextSize(14);
                    text.setGravity(Gravity.CENTER_VERTICAL);
                    text.setText(data.getList().get(i).getNickname());
                    if(i==0) {
                        Drawable drawable = getResources().getDrawable(R.drawable.undianzan);//这一步必须要做,否则不会显示.
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        text.setCompoundDrawables(drawable, null, null, null);
                        text.setCompoundDrawablePadding(3);
                    }
                    text.setLayoutParams(layoutparamas);
                    li_fav_container.addView(text);
                }
            }
        }
    }


    private void setDetailData(DongTaiDetailBean bean) {
        detailBean = bean;

        if (LocalDataManager.getInstance().getLoginInfo().getUserId().equals(bean.getUid())) {
            detail_delete.setVisibility(View.VISIBLE);
        } else {
            detail_delete.setVisibility(View.GONE);
        }
        if (bean != null) {
            if (bean.getAvatar() != null) {
//                FrescoUtil.frescoResize(
//                        SourceFactory.wrapPathToUri(bean.getAvatar()),
//                        getWidth(),
//                        getWidth(),
//                        my_me_photo

                XImageLoader.load(Const.IMAG_NEW_URL + bean.getAvatar() + ".jpg", my_me_photo);
            }
            isLike = bean.getIslike();
            if (bean.getSex() != null) {
                if (bean.getSex().equals("0")) {
                    item_billboard_tag1.setBackgroundResource(R.drawable.ic_female);
                } else {
                    item_billboard_tag1.setBackgroundResource(R.drawable.ic_male);
                }
            }
            item_billboard_tag2.setBackgroundResource(R.drawable.rank_ + Integer.parseInt(bean.getLevel().get(0).getLevelid()));
            item_billboard_name.setText(bean.getNickname());
            item_billboard_contant.setText(String2Spanned.parsed(bean.getContent()));
            item_friend_time.setText(bean.getDateline() == null ? "" : bean.getDateline());
            String[] pics = bean.getPics();
            if (pics != null) {
                if (pics.length > 0) {
                    //动态的图片
                    li_imgContainer.setVisibility(View.VISIBLE);
                    ImageGridAdapter adapter = new ImageGridAdapter(DongTaiDetailActivity.this, pics);
                    li_imgContainer.setAdapter(adapter);
                }
            } else {
                li_imgContainer.setVisibility(View.GONE);
            }
        } else {
            li_imgContainer.setVisibility(View.GONE);
        }
        replyList = bean.getReplys().getList();//获取回复列表
        DongTaiListBean.DongTaiItem.Likes likes = bean.getLikes();//获取喜欢列表
        if (replyList != null) {
            replyList.clear();
            comment_listView.setVisibility(View.VISIBLE);
            if(Integer.parseInt(bean.getReplys().getTotal_cnt())>0) {
                dongtaiPrsenter.getHuiFuList(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, pageNo + "", bean.getReplys().getTotal_cnt());
            }else{
                comment_listView.setVisibility(View.GONE);
            }

        }else{
            comment_listView.setVisibility(View.GONE);
        }
        if (likes != null) {
            if (likes.getList() != null) {
                if (likes.getList().size() > 0) {
                    dongtaiPrsenter.getDianZanList(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, "1", likes.getTotal_cnt());
                } else {
                    li_fav_container.setVisibility(View.GONE);
                }
            }else{
                li_fav_container.setVisibility(View.GONE);
            }

            item_friend_commentimg.setOnClickListener(this);
        }else{
            li_fav_container.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_send:
                String content = edit_content.getText().toString();
                if (content.equals("")) {
                    Toast.makeText(this, "请输入有效内容", 0).show();
                    return;
                }
                if (pid == null && type == 0) {
                    Toast.makeText(this, "当前评论参数有误，请刷新后重试!", 0).show();
                    return;
                }
                if (rid == null && type == 1) {
                    Toast.makeText(this, "当前回复参数有误，请刷新后重试!", 0).show();
                    return;
                }
                comment(type == 0 ? pid : rid, Spanned2String.parse(edit_content.getText()), type);
                break;
            case R.id.item_friend_commentimg://评论
                showMorePopup(v);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.delete:
                if (rid != null) {
                    publishPresenter.replyDelete(LocalDataManager.getInstance().getLoginInfo().getToken(), rid);
                } else {
                    Toast.makeText(this, "信息有误，请刷新后重试!", 0).show();
                }
                alertDialog.dismiss();
                break;
            case R.id.cancel:
                alertDialog.dismiss();
                break;
            case R.id.detail_delete:
                publishPresenter.deletePublish(LocalDataManager.getInstance().getLoginInfo().getToken(), pid);
                break;
            case R.id.emoji:
                if (!isShow) {
                    faceInputContainer.setVisibility(View.VISIBLE);
                } else {
                    faceInputContainer.setVisibility(View.GONE);
                }
                isShow = !isShow;
                break;
            case R.id.re_dianzan:

                mMorePopupWindow.dismiss();
                if (isLike == null) {
                    Toast.makeText(this, "参数有误哦,请退出后重试!", 0).show();
                    return;
                }
                publishPresenter.dianzan(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, isLike.equals("0") ? "1" : "0");

                break;
            case R.id.re_comment:
                type = 0;
                bottom.setVisibility(View.VISIBLE);
                SoftwareUtil.showOrHideSoftware(edit_content, this, true);//显示键盘
                mMorePopupWindow.dismiss();
                break;
            case R.id.my_me_photo:
                startActivity(OtherUserActivity.createIntent(this,
                        Integer.parseInt(uid), false));
                break;

        }
//        if(v.getId()!=R.id.emoji||v.getId()!=R.id.delete||v.getId()!=R.id.cancel||R.id.detail_delete!=v.getId()||R.id.txt_send!=v.getId()){
//            pid=null;
//            rid=null;
//        }

    }

    /***
     * 显示点赞 评论窗体
     *
     * @param view
     */

    public void showMorePopup(View view) {
        LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View content = li.inflate(R.layout.popup_commentorfav, null, false);
        mMorePopupWindow = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        mMorePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mMorePopupWindow.setOutsideTouchable(true);
        mMorePopupWindow.setTouchable(true);

        content.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int mShowMorePopupWindowWidth = content.getMeasuredWidth();
        int mShowMorePopupWindowHeight = content.getMeasuredHeight();

        View parent = mMorePopupWindow.getContentView();

        RelativeLayout re_dianzan = (RelativeLayout) parent.findViewById(R.id.re_dianzan);
        TextView txt_dianzan = (TextView) parent.findViewById(R.id.txt_dianzan);
        if (isLike != null) {
            if (isLike.equals("0")) {
                txt_dianzan.setText("点赞");
            } else {
                txt_dianzan.setText("取消");
            }
        }
        re_dianzan.setOnClickListener(this);
        RelativeLayout re_comment = (RelativeLayout) parent.findViewById(R.id.re_comment);
        re_comment.setOnClickListener(this);
        if (mMorePopupWindow.isShowing()) {
            mMorePopupWindow.dismiss();
        } else {
            int heightMoreBtnView = view.getHeight();

            mMorePopupWindow.showAsDropDown(view, -mShowMorePopupWindowWidth,
                    -(mShowMorePopupWindowHeight + heightMoreBtnView) / 2);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

//        if (position == replyList.size()) {
//            Toast.makeText(this, "查看更多", 0).show();
//            pageNo++;
//            dongtaiPrsenter.getHuiFuList(LocalDataManager.getInstance().getLoginInfo().getToken(), pid, pageNo + "", "10");
//        } else {
            String uid = LocalDataManager.getInstance().getLoginInfo().getUserId();
            rid = detailBean.getReplys().getList().get(position).getRid();
            if (uid.equals(detailBean.getReplys().getList().get(position).getUid())) {//执行删除
                alertDialog = new AlertDialog.Builder(DongTaiDetailActivity.this).create();
                alertDialog.show();
                Window window = alertDialog.getWindow();
                window.setContentView(R.layout.alert_delete);
                TextView tv_delete = (TextView) window.findViewById(R.id.delete);
                tv_delete.setText("删除");
                tv_delete.setOnClickListener(DongTaiDetailActivity.this);
                TextView tv_message = (TextView) window.findViewById(R.id.cancel);
                tv_message.setText("取消");
                tv_message.setOnClickListener(DongTaiDetailActivity.this);
            } else {
                type = 1;
                bottom.setVisibility(View.VISIBLE);
                SoftwareUtil.showOrHideSoftware(edit_content, this, true);//显示键盘
            }
//        }
    }

    public void comment(String id, String content, int type) {
        if (type == 0) {//回复动态
            publishPresenter.replyOne(LocalDataManager.getInstance().getLoginInfo().getToken(), id, content);
        } else {//回复回复
            publishPresenter.replyTwo(LocalDataManager.getInstance().getLoginInfo().getToken(), id, content);
        }
        bottom.setVisibility(View.GONE);
        edit_content.setText("");
        type = 0;
    }
}
